package java_thinking.unit_14._14_6_reflect;


import java_thinking.unit_14._14_2.Toy;

import java.lang.reflect.Constructor;

/**
 * @Description : 在ToyTest中，使用反射机制，通过非默认构造器创建Toy对象
 *                经典案例！！！！
 * @author: cww
 * @DateTime: 2019-03-30 20:33
 */

public class SuperToy {
    int IQ;
    public SuperToy(int intelligence) { IQ = intelligence; }
    @Override
    public String toString() {
        return "I'm a SuperToy. I'm smarter than you.";
    }
}

class ReflectionToyCreation {
    public static Toy makeToy (String toyName,int IQ) {
        try {
            Class<?> tClass = Class.forName(toyName);
            for (Constructor<?> constructor:tClass.getConstructors()){
                Class<?>[] params = constructor.getParameterTypes();
                if (params.length == 1){
                    if (params[0] == int.class){
                        return (Toy)constructor.newInstance(new Object[]{IQ});
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(makeToy("java_thinking.unit_14._14_2.Toy",150));
    }
}
